ExtGames.MayIGame = function(config) {
	
	ExtGames.MayIGame.superclass.constructor.call(this, config);

};

Ext.extend(ExtGames.MayIGame, ExtGames.Game, {
	
	newGame: function() {
	    
		  console.log('Starting New Game');
		  	  
		  this.populateHand();
		    
		  console.log('Hand Pop');
		  
		    while (c = this.pack.getTopCard()) {
		        c.move(this.decks[0]);
		      }
		    
		    var topCard = this.decks[0].getTopCard();
		    topCard.revealed = true;
			topCard.move(this.discardpiles[0]);
		    		
		    if (util.isTurn()) {
		    	
		    }
		    else {
		    	this.turn = TURN_END;
		    }
		    	    
		    console.log('New Game Started');
	  },

	nextTurn: function() {
		ExtGames.MayIGame.superclass.nextTurn.call(this);
		
		if (Ext.getCmp('mayIButton').pressed == true) {
		  Ext.getCmp('mayIButton').toggle(false);
	  	}
	},
	
	didPlay: function() {
		  var didPlay = false;
		  for (var i = 0; i < this.playareas[0].length; i++) {
			  if (this.playareas[0][i].didPlay()) {
				  didPlay = true;
			  }
		  }
		  return didPlay;
	  },
	  
	  isAllPlaysValid: function() {
		  for (var j = 0; j < this.playareas.length; j++) {
			  var didPlay = false;
			  for (var i = 0; i < this.playareas[j].length; i++) {
	      		if (this.playareas[j][i].didPlay() || didPlay) {
	      			didPlay = true;
	      			if (this.playareas[j][i].validPlay() == false) {
	      				console.log(this.playareas[j][i].itemId+' is not valid');
	      				return false;
	      			}
	      		}
	      	  }
		  }
		  return true;
	  },
	  
	  getPlayAreaCards: function() {
		  var c = [];
		  for (var i = 0; i < this.playareas[0].length; i++) {
			  c[i] = this.playareas[0][i].toObject();
		  }
		  
		  return JSON.stringify(c);
	  },
	  
	  getDiscardObject: function(card) {
		  var s = {};
		  s.card = card.toObject();
		  s.plays = [];

		  for (var j = 0; j < this.playareas.length; j++) {
			  for (var i = 0; i < this.playareas[j].length; i++) {
				  var o = this.playareas[j][i].getNewCardsObject();
				  o.pIndex = j;
				  o.aIndex = i;
				  s.plays.push(o);
			  }
		  }
		  
		  return s;
	  },
	  
	  discardedCard: function(details) {
		  
		  for (var i = 0; i < details.plays.length; i++) {
			  
			  var pIndex = details.plays[i].pIndex;
			  var aIndex = details.plays[i].aIndex;
			  
			  pIndex = (pIndex+turnIndex)%util.getNumP();
			  var areas = this.playareas[pIndex];
			  
			  var area = areas[aIndex];
			  
			  for (var j = 0; j < details.plays[i].cards.length; j++) {
				  var card = hand.findCard(details.plays[i].cards[j]);			  
				  card.move(area, card.pos);
			  }
			  
			  area.saveCards();
		  }
		  
		  ExtGames.MayIGame.superclass.discardedCard.call(this, details);
		  
		  
	  },
	  
	  getScores: function() {
		  var scorecard = [];
		  
		  for (var i = 0; i < this.hands.length; i++) {
			  cards = this.hands[i].toObject();
			  		  
			  points = 0;
			  for (var j = 0; j < cards.length; j++) {
				  points += getCardPoints(cards[j]);
			  }
			  scorecard[i] = points;
		  }
		  
		  return scorecard;
	  },

	mayIRecieved: function(requestId) {
	  	if (this.mayI == null) {
	  		this.mayI = requestId;
	  	}
	  	else {
	  		var opp = util.getOpponents();
	  		for (var i = 0; i < opp.length; i++) {
	  			if (opp[i].id == this.mayI) {
	  				return;
	  			}
	  			if (opp[i].id == requestId) {
	  				this.mayI = requestId;
	  				return;
	  			}
	  		}
	  	}
	  	
	  	this.updateStatusCallMayI(util.getName(requestId));
	},
	
 	callMayI: function() {
	  if (this.turn != TURN_END) {
	  	  Ext.getCmp('mayIButton').toggle(false);
		  return;
	  }
	  
	  if (Ext.getCmp('mayIButton').pressed == true) {
		  util.submitMayIRequest();
		  this.updateStatusCallMayI(util.getName(util.getMyId()));
	  }
    },

	getRoundCriteria: function() {
	  var cardsLeft = this.getNumberOfCardsToDeal()-1;	
	  var runs = parseInt(cardsLeft/4);
	  while ((cardsLeft - runs*4)%3 != 0) {
		  runs--;
	  }
	  var groups = (cardsLeft - runs*4)/3;
	  	  
	  var round = {};
	  round['runs'] = runs;
	  round['groups'] = groups;
	  	  
	  return round;
  	},
  	
  	isGameEnd: function() {
  		return((this.round+1) == 9); 
  	},

	getNumberOfCardsToDeal: function() {
		return 8 + this.round;
	},
	
	getNumberOfHandsPerPerson: function() {
		return 1;
	},
	
	getAddHandComp: function() {
		this.playareas = [];
		this.playareas[0] = [];
		
		var round = this.getRoundCriteria();
		var runs = parseInt(round['runs']);
		var groups = parseInt(round['groups']);
			
		var i = 0;
			
		for (i = 0; i < runs; i++) {
			this.playareas[0][i] = new ExtGames.MayIPlayArea({
				itemId: 'playarea_run_' + i,
				type: 0,
				opp: 0,
				listeners: {
		            'carddropped': {
		            	fn: this.dropCard,
		            	scope: this,
		            }
		          }
		        });  
		}
		
		for (; i < (groups+runs); i++) {
			this.playareas[0][i] = new ExtGames.MayIPlayArea({
				itemId: 'playarea_group_' + i,
				type: 1,
				opp: 0,
				listeners: {
		            'carddropped': {
		            	fn: this.dropCard,
		            	scope: this,
		            }
		          }
		        });  
		}
		
		var opp = util.getOpponents();
			
		for (var j = 0; j < opp.length; j++) {
			this.playareas[j+1] = [];
			for (i = 0; i < runs; i++) {
				this.playareas[j+1][i] = new ExtGames.MayIPlayArea({
					itemId: 'playarea_'+j+'_run_' + i,
					type: 0,
					opp: 1,
					listeners: {
			            'carddropped': {
			            	fn: this.dropCard,
			            	scope: this,
			            }
			          }
			        });  
			}
			
			for (; i < (groups+runs); i++) {
				this.playareas[j+1][i] = new ExtGames.MayIPlayArea({
					itemId: 'playarea_'+j+'_group_' + i,
					type: 1,
					opp: 1,
					listeners: {
			            'carddropped': {
			            	fn: this.dropCard,
			            	scope: this,
			            }
			          }
			        });  
			}
		}
		
		console.log('Created Playareas');
		
		return this.playareas;
	},
	
	getToolbarButtons: function() {
		var buttons = [];
		buttons.push(new Ext.Button({
		    id: 'mayIButton',
		    text:    'May I',
		    enableToggle: true,
		    allowDepress: false,
		    scope:   this,
		    toggleHandler: function(button, state) {
		      game.callMayI();
		    }
		}));
		
		return buttons;
	},
	
	splashOnly: function() {
		return((this.round+1) == 9); 
	},
	
	updateStatusCallMayI: function(name) {
	  var s = name+' called May I';
	  this.win.updateStatus(s);
  	},
  
  	updateStatusMayI: function(fromName, toName) {
	  	var s = toName+' did a May I. '+fromName+' drew a card from the deck.';
	  	this.win.updateStatus(s);
  	},
  	
  	giveMayICards: function() {
  		var card1 = this.discardpiles[0].getTopCard();
  	    var card2 = this.decks[0].getTopCard();
  	     var opphand = this.hands[util.getOpponentIndex(this.mayI)];
  	       	     
  	     card1.hide();
  	     card1.move(opphand);
  	     var s = {};
		 s.from = 'discardPile_0';
		 s.card = card1.toObject();
		 util.submitMayICards(this.mayI, s);
  	       	     
  	     card2.move(opphand);
  	     s = {};
		 s.from = 'deck_0';
		 s.card = card2.toObject();
		 util.submitMayICards(this.mayI, s);
  	},
  	
  	dropCard: function(stack, card, e) {	  
	  	  
  	  var from = card.location.itemId;
  	  var to = stack.itemId;
  	  
  	  console.log('DROP CARD from '+from+' to '+to);
  	  	  
  	  if (from == 'hand' && to == 'hand') {
  	  	  this.hands[0].rearrange(card, e);
  	  	  return;
  	  }
  	  
  	  if (this.turn == TURN_START) {
  		  if (!isDeck(from) && !isDiscardPile(from)) {
  		  	 return;
  		  }
  	  
  		  if (isDeck(from)) {
  		  	
  		  	  if (this.mayI) {
  		  	     this.giveMayICards();
  				 card = this.decks[0].getTopCard();
  		  	  }
  				  	
  			  card.reveal();
  		  }
  				  
  		  card.move(stack);
  		  this.hands[0].sortCards();
  		  this.mayI = null;
  		  
  		  var s = {};
  		  s.from = from;
  		  s.card = card.toObject();
  		  util.drawCard(s);
  			
  		  this.turn = TURN_PLAY;
  		  
  		  this.win.updateStatus('You drew a '+card.toPlainText());
  			  
  	  }
  	  else if (this.turn == TURN_PLAY) {
  		  
  		  if (isDiscardPile(from) || isDeck(from) || isOppHand(from)) {
  	  		return;
    	  }
  	  
  		  if (cCmp(from, 'play')) {
  			  
  			  if (to == from) {
  			  	  stack.rearrange(card,e);
  			  	  return;
  			  }
  			  
  			  if (card.location.isSaved(card) == true) {
  			  	  return;
  			  }
  		  }
  		 
  		  if (isDiscardPile(to)) {
  			 
  			  var didPlay = this.didPlay();
  			  
  			  if (this.isAllPlaysValid() == false) {
  				  return;
  			  }
  			  if (didPlay == true && this.splashOnly() == true) {
  			  	  return;
  			  }
  			  
  			  card.move(stack);
  			  util.discard(this.getDiscardObject(card));
  			  
  			 this.turn = TURN_END;
  			  
  			  if (didPlay) {
  				  for (var j = 0; j < this.playareas.length; j++) {
  					  for (var i = 0; i < this.playareas[j].length; i++) {
  						  this.playareas[j][i].saveCards();
  					  }
  				  }
  				  
  			  }
  			  
  			  if (this.hands[0].getNumCards() == 0) {
  				  this.endRound();
  			  }
  			  else {
  				  util.endTurn();
  			  }
  			  
  		  }
  		  else if (cCmp(to, 'play')) {
  		  			
  		  	  card.move(stack);
  		  		
  		  	  if (this.hands[0].getNumCards() == 0) {	
  			  	  
  		  		var didPlay = this.didPlay();
  				  
  				  if (this.isAllPlaysValid() == false) {
  					  return;
  				  }
  				
  				util.discard(this.getDiscardObject(card));
  				this.endRound();
	  		  }
	  		  else {
	  			  var joker = stack.replaceJoker(card);
	  		  }  
	  					  	
	  		}
	  		else {
	  			card.move(stack);
	  		}
  	  
  	  }
  	  
    }

});